import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  DeviceEventEmitter,
  Platform,
  TextInput,
  Image,
  Dimensions,
  NativeAppEventEmitter,
  InteractionManager,
  ProgressBarAndroid,
} from 'react-native';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import styles from './indexStyle';
import ProgressBar from '../global/ProgressBar';
import DefaultTabBar from '../global/scrollableTabView/DefaultTabBar';
import Button from '../global/scrollableTabView/Button';
import DeviceStorage from '../global/DeviceStorage';
import Touch from '../global/Touch';
import Toast from 'react-native-sk-toast';

import JPushModule from 'jpush-react-native';

import EasemobChat from '../global/EasemobChat';

import api from '../../services/api';
import OrderList from './orderList';
import SimpleDialog from '../global/SimpleDialog';
import CancelOrderReasonDialog from './cancelOrderReasonDialog';
import {Loading, EasyLoading} from '../global/EasyLoading';
import { Navigation } from '../global/navigation/index';
var windowWidth = Dimensions.get('window').width;
const percent = 0.078125; // 弹窗左右间距百分比
let margin = windowWidth * percent; // 弹窗左右间距

class Order extends Component {
    constructor(props) {
		super(props);

		this.state = {
			isLoading: true,
			isRefreshing: false,
            searchText: '',
			tab: 0,
            topage: -1,
            num: [0,0,0],
            cancelOrderId:-1,
            showCancelOrderDialog:false,
            handSignOrderId:-1,
            openHandSignDialog:false
		};

		// this._getTabHeight = this._getTabHeight.bind(this);
		this._onChangeTab = this._onChangeTab.bind(this);
        this.searchStrArr = ["", "", ""];
        this.searchStr = "";
        this.saveOrder = 1;

		this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
        this._subcribGotoPage = DeviceEventEmitter.addListener("gotoPage",this.gotoPage.bind(this));

        this._subcribAddTask = DeviceEventEmitter.addListener("addTask", (res)=>{
          let {session} = this.props;
          let title = session && session.user && session.user.productKey == "HuLiZhan" ? "新增护理服务":"新增任务"
            this.props.navigator.push({
                     title: title,
                     screen: 'housekeeperapp.addorder',
                     backButtonTitle:'',
                      passProps: {
                          source: 'create',
                          userPhone: res.phone,
                      },
                      navigatorStyle:{
                        tabBarHidden: true,
                        navBarTextColor: 'white',
                        navBarButtonColor: 'white',
                        navBarBackgroundColor: '#EA5404',
                        statusBarColor: '#EA5404',
                        navBarTitleTextCentered: true,
                        topBarElevationShadowEnabled:false
                    },
                    navigatorButtons: {
                      rightButtons: [
                          {
                              id: 'clear',
                              testID: 'order_clear',
                              title: '清空'
                          }
                      ],
                      leftButtons:[
                          {
                              id: 'back',
                              icon: require("../../../img/hk_back_icon.png")
                          }
                      ]
                  }
              });
        });

        this._subcribOrderDetail = DeviceEventEmitter.addListener("orderDetail", (res)=>{
            this.props.navigator.push({
                title: "订单详情",
                backButtonTitle:'',
    			screen: 'housekeeperapp.orderdetail',
    			passProps: {
    				orderId: res.orderId
    			},
                navigatorStyle:{
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
    			// backButtonHidden: true,
    			navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ],
    				rightButtons: [
    					{
    						id: 'reload',
                            testID: 'order_reload',
    						title: '刷新'
    					}
    				]
    			}
    		});
        });

        // 接受自定义消息
        JPushModule.notifyJSDidLoad((resultCode) => {
          
        });

	}
    componentWillMount() {
		// this._retrieveDetails();
        // 清空所有数据
        // DeviceStorage.deleteArr(["@order@send","@order@buy","@order@express","@order@lockkey","@order@other"]);
	}

    gotoPage(num){
        if(num == null || num == undefined || typeof num == 'object'){
            num = 1;
        }

        this.setState({
            topage: num
        });
    }

    async _onNavigatorEvent(event){
      let {session} = this.props;
      let title = session && session.user && session.user.productKey == "HuLiZhan" ? "新增护理服务":"新增任务"

        if (event.type == 'NavBarButtonPress') {
              if (event.id == 'add') {
                  if(this.state.isDisable){
                      return;
                  }

                  await this.setState({isDisable:true});//防重复点击
                  this.props.navigator.push({
                           title: title,
              			   screen: 'housekeeperapp.addorder',
                           backButtonTitle:'',
                  			passProps: {
                  				source: 'create'
                  			},
                            navigatorStyle:{
                              tabBarHidden: true,
                              navBarTextColor: 'white',
                          	  navBarButtonColor: 'white',
                          	  navBarBackgroundColor: '#EA5404',
                              statusBarColor: '#EA5404',
                              navBarTitleTextCentered: true,
                              topBarElevationShadowEnabled:false
                          },
                          navigatorButtons: {
                              leftButtons:[
                                  {
                                      id: 'back',
                                      icon: require("../../../img/hk_back_icon.png")
                                  }
                              ],
              				rightButtons: [
              					{
              						id: 'clear',
                                    testID: 'order_clear',
              						title: '清空'
              					}
              				]
              			}
              		});

                    this.timer = setTimeout(async()=>{
                        await this.setState({isDisable:false});//1.0秒后可点击
                    },1000);
              }
        }

        // if(event.id == 'backPress'){
        //     EasemobChat.backToNativeView();
        // }
        // 
    }

    componentDidMount(){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        this._subcribOrder = Emitter.addListener('order.onload', this.onLoad.bind(this));
        // this._subcribSign = Emitter.addListener('hand.sign.success', this._handWritingSignSuccess.bind(this));

        this._getOrderCount();

        JPushModule.removeReceiveCustomMsgListener(this.customMsg);
        JPushModule.removeReceiveOpenNotificationListener(this.openMsg);
        JPushModule.addReceiveCustomMsgListener(this.customMsg);
        JPushModule.addReceiveOpenNotificationListener(this.openMsg);
    }

    customMsg = (message) =>{
        console.log('testcustomMsgcustomMsgcustomMsgcustomMsgcustomMsgcustomMsg',message);
        let robOrder = (message.message && message.message.indexOf("快来抢单") != -1);
        let orderId = JSON.parse(message.extras).id;
        // if(robOrder && orderId == this.saveOrder){
        //     return;
        // }

        EasemobChat.showOrderDialog(message);
        // this.saveOrder = orderId;
    }

    openMsg = (message) => {
        if(message.alertContent && message.alertContent.indexOf("转单超3分钟无人抢单") != -1){
            let {navigator} = this.props;
            let orderId = JSON.parse(message.extras).id;

    		navigator.push({
                title: "订单详情",
                backButtonTitle:'',
    			screen: 'housekeeperapp.orderdetail',
    			passProps: {
    				orderId
    			},
                navigatorStyle:{
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
    			// backButtonHidden: true,
    			navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ],
    				rightButtons: [
    					{
    						id: 'reload',
                            testID: 'order_reload',
    						title: '刷新'
    					}
    				]
    			}
    		});
        }
    }

    async _getOrderCount(){
        let res, arr = [];
        res = await api.post('/order/listcount',{status: 1});
        if(res){
            arr.push(res.data);
        }
        //待服务
        res = await api.post('/order/listcount', {
                      status: 2
                   });

        if(res){
            arr.push(res.data);
        }
        //服务中
        res = await api.post('/order/listcount', {
                      status: 3
                   });

        if(res){
            arr.push(res.data);
        }

        this.setState({ num : arr});
    }

    _onChangeTab({ i, ref }) {
        let {tab} = this.state;
        if(tab == i){
            return;
        }

		this.setState({ tab: i, topage: i, searchText: this.searchStrArr[i]});
	}

  // _handWritingSignSuccess(){
  //   console.log('_handWritingSignSuccess=====================',"=====================");
  //   this.setState({
  //     handSignOrderId:-1,
  //     openHandSignDialog:false
  //   })
  // }

    onLoad(data, searchStr){
        this.searchStr = searchStr;
        // this.setState({handSignOrderId:-1,openHandSignDialog:false})

        // InteractionManager.runAfterInteractions(async() => {
        //
        //
        // });

        this._newTakeListView && this._newTakeListView.wrappedInstance.onLoad(data, this.searchStrArr[0]);
        this._notTakeListView && this._notTakeListView.wrappedInstance.onLoad(data, this.searchStrArr[1]);
        this._takedListView && this._takedListView.wrappedInstance.onLoad(data, this.searchStrArr[2]);

        this._getOrderCount();
    }

    // _onNavigatorEvent(event){
    //     if (event.type === 'ScreenChangedEvent') {
	// 		if (event.id === 'didAppear') {//出现时
    //
	// 		}
	// 	}
    // }

    componentWillUnmount(){
        this._subcribOrder && this._subcribOrder.remove();
        this._subcribGotoPage && this._subcribGotoPage.remove();
        this._subcribAddTask && this._subcribAddTask.remove();
        this._subcribOrderDetail && this._subcribOrderDetail.remove();
        // this._subcribSign && this._subcribSign.remove();

        this.timer && clearTimeout(this.timer);

        // JPushModule.removeReceiveCustomMsgListener(this.customMsg.bind(this));
        // JPushModule.removeReceiveOpenNotificationListener(this.openMsg.bind(this));
    }

    updateMarkNum(page, num){
        let arr = this.state.num;
        if(num <= 0){
            arr[page] = 0;
        }else{
            arr[page] = num;
        }

        this.setState({ num : arr});
    }

    getMarkNum(){
        return this.state.num;
    }

    _renderTab(name, page, isTabActive, onPressHandler) {
      const {textStyle, markStyle, markTextStyle, } = styles;
      const textColor = isTabActive ? '#EA5404' : '#555555';
      const fontWeight = isTabActive ? '500' : 'normal';
      const markDom = (this.state.num[page]?<View style={markStyle}><Text style={markTextStyle}>{this.state.num[page]>99?"99+":this.state.num[page]}</Text></View>:null);

      return <Button
        style={{flex: 1, }}
        key={name}
        accessible={true}
        accessibilityLabel={name}
        accessibilityTraits='button'
        onPress={() => onPressHandler(page)}
      >
        <View style={[{flex:1,alignItems: 'center',justifyContent: 'center',paddingBottom: 10}, this.props.tabStyle, ]}>
          <Text style={[textStyle, {color: textColor, fontWeight, }, ]}>
            {name}
          </Text>
          {markDom}
        </View>
      </Button>;
    }

    async _rightAdd(){
        if(this.state.isDisable){
            return;
        }
        let {session} = this.props;
        let title = session && session.user && session.user.productKey == "HuLiZhan" ? "新增护理服务":"新增任务"

        await this.setState({isDisable:true});//防重复点击
        this.props.navigator.push({
                 title: title,
                 screen: 'housekeeperapp.addorder',
                 backButtonTitle:'',
                  passProps: {
                      source: 'create'
                  },
                  navigatorStyle:{
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                    navBarButtonColor: 'white',
                    navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
                navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ],
                  rightButtons: [
                      {
                          id: 'clear',
                          testID: 'order_clear',
                          title: '清空'
                      }
                  ]
              }
          });

          this.timer = setTimeout(async()=>{
              await this.setState({isDisable:false});//1.0秒后可点击
          },1000);
    }

    _onSubmitEditing(){
        this._textInput && this._textInput.blur();
    }

    _onPressSearch(event){
       //搜索请求
       this.onLoad(null, event.nativeEvent.text);
    }


    async _cancelOrder(id,reason){
        let {turn,service_type} = this.state;
        this.setState({open: false});
        let res;

        if(turn == 1){// 管家和业主转单
            res = await api.post("/order/turn",{id:id});
        }else{
          if (service_type && service_type == "shops") {
            this._refundShopMoney(id);
          }
          if (service_type && service_type == "activity") {
            this._cancelActivityOrder(id)
          }

          res = await api.post("/order/updatestatus",{id:id,status:-1,cancelReason:reason});
        }

        if(res.data){
            if(turn == 1){
              Toast.bottom("转单成功");
            }else{
              this.setState({
                cancelOrderId:-1,
              })
              this.refs.cancelOrderDialog._hide();
              // this._hideLoading();
            }
            this.onLoad(null, this.searchStr);
        }else{
            turn == 1?Toast.bottom("转单失败"):Toast.bottom("取消订单失败");
            this.onLoad(null, '');
            // this._hideLoading();
        }
    }

    async _refundShopMoney(id){
        let result = await api.post("/privilege/shops/orderRefund",{oid:id})
        // if (result.cd != 0) {
        //     Toast.bottom(result.msg);
        //     // this.onLoad(null, '');
        // }else{
        //     Toast.bottom("取消订单成功");
        //     // this.onLoad(null, this.searchStr);
        // }
    }

    // 取消活动报名订单
    async _cancelActivityOrder(id){
        let result = await api.post("/configurable/cancelOrder",{id})
    }

    _clearStr(){
        let {tab} = this.state;
        this._textInput && this._textInput.blur();
        this.setState({searchText:''});

        this.searchStrArr[this.state.tab] = "";
        this.onLoad(null, '');
    }

    _renderDialog(id) {
        let {turn} = this.state;
        let line1 = "", line2 = "";
        let cancel = "暂不";
        if(turn == 1){
            line1 = "确定发起转单吗？";
            line2 = "发起后，订单将不会显示在列表中";
            cancel = "取消";
            return (
              <SimpleDialog
                  offset={0}
                  showModal={this.state.open}
                  closeOnTouchOutside={false}
                  dialogContainerStyle={{marginLeft:60,marginRight:60,marginTop: 240}}
                  parent={this}
                  modalDidOpen={() => console.log('modal did open')}
                  modalDidClose={() => console.log('modal did close')}>
                      <View style={styles.dialogContainer}>
                          <View style={{alignItems:'center',marginTop:40}}>
                              <Text style={styles.dialogBodyText}>
                                  {line1}
                              </Text>
                              <Text style={styles.dialogBodyText}>
                                  {line2}
                              </Text>
                          </View>
                          <View style={[styles.submitBtnContainer,{marginTop:40}]}>
                              <Touch onPress={()=>{this.setState({open: false})}} style={styles.submitCancelBtn}>
                                  <Text style={styles.submitBtnText}>{cancel}</Text>
                              </Touch>
                              <Touch onPress={this._cancelOrder.bind(this, id)} style={styles.submitOkBtn}>
                                  <Text style={[styles.submitBtnText,{color:'#EA5404'}]}>确定</Text>
                              </Touch>
                          </View>
                      </View>
                </SimpleDialog>
          )
        }else{
          return null;
        }
        // else{
        //     line1 = "取消前请先和用户确认，";
        //     line2 = "确定取消吗？";
        // }

        
    }
    _showLoading(){
      this.loadingCont = this.refs.loading;
      this.loadingCont.setState({ "isShow": true, "text": '加载中...' });
    }
    _hideLoading(){
      this.loadingCont = this.refs.loading;
      this.loadingCont.setState({ "isShow": false });
    }


    _onConfirmCancelOrder(reason){
      if (reason) {
        this.setState({
           showCancelOrderDialog:false,
        })
        // this._showLoading();
        this._cancelOrder(this.state.cancelOrderId,reason);
      }else{
        Toast.bottom('请输入取消原因');
      }
      
    }

    _onCancelCancelOrder(){
      this.setState({
        cancelOrderId:-1,
        showCancelOrderDialog:false,
      })
    }

    _renderCancelOrderDialog(orderId){
      if (orderId != -1) {
        return (<CancelOrderReasonDialog ref="cancelOrderDialog" showModal={this.state.showCancelOrderDialog} onCancel={this._onCancelCancelOrder.bind(this)} onConfirm={this._onConfirmCancelOrder.bind(this)}/>)
      }else{
        return null;
      }
      
    }

    _renderHandSignDialog(){
        return (
            <SimpleDialog
                offset={0}
                showModal={this.state.openHandSignDialog}
                closeOnTouchOutside={true}
                dialogContainerStyle={{marginLeft:40,marginRight:40,marginTop: 240}}
                parent={this}
                modalDidOpen={() => console.log('modal did open')}
                modalDidClose={() => console.log('modal did close')}>
                    <View style={styles.dialogContainer}>
                        <View style={{alignItems:'center',marginTop:40}}>
                            <Text style={styles.dialogBodyText}>
                                请用户进行签名
                            </Text>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:40}]}>
                            <Touch onPress={() =>{this.setState({openHandSignDialog: false})}} style={styles.submitCancelBtn}>
                                <Text style={styles.submitBtnText}>暂不签名</Text>
                            </Touch>
                            <Touch onPress={this._openHandSignActivity.bind(this)} style={styles.submitOkBtn}>
                                <Text style={[styles.submitBtnText,{color:'#EA5404'}]}>立即签名</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }

    _openHandSignActivity(){
        let {handSignOrderId} = this.state;
        Navigation.startHandSignActivity({order_id:handSignOrderId});
        this.setState({handSignOrderId:-1,openHandSignDialog:false})
    }

    renderView(){
        let {cur_id,orderId} = this.state;
        if(!this.props.session.user){
            return null;
        }

        let user_role = this.props.session.user.role;
        if(user_role == 1){//消息中心
            return (
                <View style={{flex:1}}>
                    <View style={styles.navBarStyle}>
                        <View style={styles.barSearch}>
                            <Image source={require('../../../img/search_edit_icon.png')} style={styles.leftImage}/>
                            <TextInput
                                value={this.state.searchText}
                                onChangeText={(text)=>{
                                    this.searchStrArr[this.state.tab] = text;
                                    this.setState({searchText: text});
                                }}
                                ref={component => this._textInput = component}
                                onSubmitEditing={this._onSubmitEditing.bind(this)}
                                onEndEditing={this._onPressSearch.bind(this)}
                                returnKeyType='search'
                                style={styles.searchLeft}
                                editable = {true}
                                multiline={false}
                                underlineColorAndroid={'#FFEBE1'}
                                placeholder={'请输入地址或手机号搜索'}
                                placeholderTextColor={'#7B7B7B'}
                            />
                            {this.state.searchText?<Touch activeOpacity={0.7} onPress={this._clearStr.bind(this)}>
                                <Image resizeMode={'cover'} source={require('../../../img/icon_input_delete.png')} style={styles.closeImage}/>
                            </Touch>:null}
                        </View>
                        <Touch style={styles.searchRight} activeOpacity={0.7} onPress={this._rightAdd.bind(this)}>
                            <Text style={[styles.searchRightBtn]}>新增任务</Text>
                        </Touch>
                    </View>
                    <ScrollableTabView
                        onChangeTab={this._onChangeTab}
                        locked={Platform.OS === 'android'?true:false}
                        renderTabBar={() => (
                            <DefaultTabBar
                                ref={component => this.tabBar = component}
                                activeTextColor={"#EA5404"}
                                textStyle={styles.textStyle}
                                renderTab={this._renderTab.bind(this)}
                                markStyle={styles.markStyle}
                                markTextStyle={styles.markTextStyle}
                                underlineStyle={styles.underlineStyle}
                                style={styles.tabBar}
                            />
                        )}>
                        <OrderList
                            tabLabel="新任务"
                            tab={0}
                            status={0}
                            parent={this}
                            ref={(component) => this._newTakeListView = component }
                            navigator={this.props.navigator}/>
                        <OrderList
                            tabLabel="待服务"
                            tab={1}
                            status={2}
                            ref={(component) => this._notTakeListView = component }
                            parent={this}
                            navigator={this.props.navigator}/>
                        <OrderList
                            tabLabel="服务中"
                            tab={2}
                            status={3}
                            parent={this}
                            ref={(component) => this._takedListView = component }
                            navigator={this.props.navigator}/>
                    </ScrollableTabView>
                    {this._renderDialog(cur_id)}
                    {this._renderCancelOrderDialog(orderId)}
                    {this._renderHandSignDialog()}
                    <Loading ref="loading"/>
                </View>
            )
        }else if(user_role == 0 || user_role == 2){
            return (
                <View style={{flex:1}}>
                    <View style={[styles.navBarStyle,{justifyContent: 'center', alignItems: 'center'}]}>
                        <Text style={{textAlign:'center',fontSize: 18, color: '#fff'}}>订单</Text>
                    </View>
                    <ScrollableTabView
                        onChangeTab={this._onChangeTab}
                        page={this.state.topage}
                        locked={Platform.OS === 'android'?true:false}
                        renderTabBar={() => (
                            <DefaultTabBar
                                ref={component => this.tabBar = component}
                                activeTextColor={"#EA5404"}
                                textStyle={styles.textStyle}
                                renderTab={this._renderTab.bind(this)}
                                markStyle={styles.markStyle}
                                markTextStyle={styles.markTextStyle}
                                underlineStyle={styles.underlineStyle}
                                style={styles.tabBar}
                            />
                        )}>
                        <OrderList
                            tabLabel="新任务"
                            tab={0}
                            status={0}
                            parent={this}
                            ref={(component) => this._newTakeListView = component }
                            navigator={this.props.navigator}/>
                        <OrderList
                            tabLabel="待服务"
                            tab={1}
                            status={2}
                            ref={(component) => this._notTakeListView = component }
                            parent={this}
                            navigator={this.props.navigator}/>
                        <OrderList
                            tabLabel="服务中"
                            tab={2}
                            status={3}
                            parent={this}
                            ref={(component) => this._takedListView = component }
                            navigator={this.props.navigator}/>
                    </ScrollableTabView>
                    {this._renderDialog(cur_id)}
                    {this._renderHandSignDialog()}
                </View>
            )

        }
    }

    render() {
        return this.renderView();
    }
}

var connectHelper = require('../../services/connectHelper');
Order = connectHelper(state => state)(Order);

module.exports = Order;
